package com.broker.utils.events.support.kafka.demo;

import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;

import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Properties;

/**
 * @author Daizhiqiang <zqdai@sailfish.com.cn>
 * create by 2020/3/23 12:42
 * Description: echatimbroker
 **/
public class KafkaConsumerMainDemo {
    private static final String mqServerUrl = "192.168.0.6:9092";

    public static void main(String[] args) {
        Properties props = new Properties();
        props.put("bootstrap.servers", KafkaDemoConfig.MQ_SERVER_URL);
        props.put("group.id", "test");
        props.put("enable.auto.commit", "true");
        props.put("auto.commit.interval.ms", "1000");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        final KafkaConsumer<String, String> consumer = new KafkaConsumer<String,String>(props);
        consumer.subscribe(Arrays.asList(KafkaDemoConfig.MQ_TOPIC),new ConsumerRebalanceListener() {
            public void onPartitionsRevoked(Collection<TopicPartition> collection) {
            }
            public void onPartitionsAssigned(Collection<TopicPartition> collection) {
                //将偏移设置到最开始
//                consumer.seekToBeginning(collection);
                //将偏移设置到最后
                consumer.seekToEnd(collection);
            }
        });
        while (true) {
//            ConsumerRecords<String, String> records = consumer.poll(100);
            ConsumerRecords<String, String> records = consumer.poll(0);
            for (ConsumerRecord<String, String> record : records){
                System.out.printf("offset = %d, key = %s, value = %s, msg delay = %d ms %n", record.offset(),
                        record.key(),
                        record.value(),
                        (new Date().getTime() - Long.parseLong(record.value().split("_")[1])));
            }
        }
    }
}
